package cn.ssms.util;

import java.io.FileOutputStream;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

import sun.misc.BASE64Decoder;

public class MyUtils {
	public static boolean isMobile(String str) {    
		Pattern p = null;   
		Matcher m = null;   
		boolean b = false;    
		p = Pattern.compile("^[1][3,4,5,8][0-9]{9}$"); // 验证手机号   
		m = p.matcher(str);   
		b = m.matches();    
		return b;   
	} 
	public static String getIpAddr(HttpServletRequest request) {
		String ipAddress = null;
		// ipAddress = this.getRequest().getRemoteAddr();
		ipAddress = request.getHeader("x-forwarded-for");
		if (ipAddress == null || ipAddress.length() == 0
				|| "unknown".equalsIgnoreCase(ipAddress)) {
			ipAddress = request.getHeader("Proxy-Client-IP");
		}
		if (ipAddress == null || ipAddress.length() == 0
				|| "unknown".equalsIgnoreCase(ipAddress)) {
			ipAddress = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ipAddress == null || ipAddress.length() == 0
				|| "unknown".equalsIgnoreCase(ipAddress)) {
			ipAddress = request.getRemoteAddr();
			if (ipAddress.equals("127.0.0.1")) {
				// 根据网卡取本机配置的IP
				InetAddress inet = null;
				try {
					inet = InetAddress.getLocalHost();
				} catch (UnknownHostException e) {
					e.printStackTrace();
				}
				ipAddress = inet.getHostAddress();
			}

		}
		// 对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
		if (ipAddress != null && ipAddress.length() > 15) { // "***.***.***.***".length()
															// = 15
			if (ipAddress.indexOf(",") > 0) {
				ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
			}
		}
		return ipAddress;
	}
	
	public static String saveIcon(String image,String path,String userId){
		String b[] = image.split(";base64,");

		String img[] = b[0].split("/");

		String header = "data:image/" + img[1] + ";base64,";

		image = image.substring(header.length());
	
		// 去掉头部
		String filename = "LOGO" +  userId + "." + img[1];
		// 写入磁盘
		BASE64Decoder decoder = new BASE64Decoder();
		try {
			byte[] decodedBytes = decoder.decodeBuffer(image);
			String imgFilePath =path+"\\"+filename;
					/*request.getSession().getServletContext()
					.getRealPath("/")
					+ filename;*/
			FileOutputStream out = new FileOutputStream(imgFilePath);
				
			out.write(decodedBytes);
			out.close();
			return filename;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
}
